package cn.objectspace.filessh.service.impl;

import cn.objectspace.filessh.exception.BusinessException;
import cn.objectspace.filessh.mapper.UserConnectMapper;
import cn.objectspace.filessh.mapper.UserMapper;
import cn.objectspace.filessh.service.IUserService;
import cn.objectspace.filessh.user.pojo.SshUser;
import cn.objectspace.filessh.vo.SshUserVo;
import cn.objectspace.util.MD5Util;
import cn.objectspace.util.SshCodeMsg;
import cn.objectspace.util.TokenGenerator;
import cn.objectspace.util.ValidationUtils;
import cn.objectspace.webssh.pojo.SshConnect;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author pc
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;
    @Resource
    UserConnectMapper userConnectMapper;
    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public boolean register(SshUser user) {

        if (user.getPassword() == null && user.getUsername() == null) {
            throw new BusinessException(SshCodeMsg.USERNAME_PASSWORD_NULL);
        }
        if (user.getPassword() == null) {
            throw new BusinessException(SshCodeMsg.PASSWORD_NULL);
        }
        if (user.getUsername() == null) {
            throw new BusinessException(SshCodeMsg.USERNAME_NULL);
        }

        //判断是否注册过
        QueryWrapper<SshUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        List<SshUser> userList = userMapper.selectList(queryWrapper);
        if (userList.size() != 0) {
            throw new BusinessException(SshCodeMsg.LOGIN_USERNAME_ERROR);
        }


        //进行格式验证
        boolean validPhoneNumber = ValidationUtils.isValidPhoneNumber(String.valueOf(user.getPhone()));
        if (!validPhoneNumber) {
            throw new BusinessException(SshCodeMsg.PHONE_ERROR);
        }
        boolean validEmail = ValidationUtils.isValidEmail(user.getEmail());
        if (!validEmail) {
            throw new BusinessException(SshCodeMsg.EMAIL_ERROR);
        }
        //对用户输入的用户名和密码进行长度的校验
        if (!ValidationUtils.isLengthValid(user.getUsername())) {
            throw new BusinessException(SshCodeMsg.REGISTER_ERROR_LENGTH);
        }
        if (!ValidationUtils.isLengthValid(user.getPassword())) {
            throw new BusinessException(SshCodeMsg.REGISTER_ERROR_LENGTH);
        }
        //对用户的密码进行MD5加密
        user.setPassword(MD5Util.getMD5(user.getPassword()));
        user.setRole(1);
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return true;
        } else {
            return false;
        }


    }

    /**
     * 用户登录
     *
     * @param user 表单数据
     * @return token
     */
    @Override
    public String login(SshUserVo user) {


        if (user.getPassword() == null && user.getUsername() == null) {
            throw new BusinessException(SshCodeMsg.USERNAME_PASSWORD_NULL);
        }
        if (user.getPassword() == null) {
            throw new BusinessException(SshCodeMsg.PASSWORD_NULL);
        }
        if (user.getUsername() == null) {
            throw new BusinessException(SshCodeMsg.USERNAME_NULL);
        }

        //判断用户名是否存在
        QueryWrapper<SshUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        List<SshUser> userList = userMapper.selectList(queryWrapper);

        if (userList.size() == 0) {
            throw new BusinessException(SshCodeMsg.LOGIN_USERNAME_ERROR);
        }
        SshUser sshUser = userList.get(0);
        //判断密码是否正确
        if (MD5Util.getMD5(user.getPassword()).equals(sshUser.getPassword())) {
            String token = TokenGenerator.generateToken();
            //设置token过期时间为一小时
            redisTemplate.opsForValue().set(token, String.valueOf(sshUser.getUserId()), 3600, TimeUnit.SECONDS);
            return token;
        } else {
            throw new BusinessException(SshCodeMsg.LOGIN_PASSWORD_ERROR);
        }


    }

    /**
     * 管理员登录
     *
     * @param user 表单用户
     * @return token
     */
    @Override
    public String adminLogin(SshUserVo user) {

        //判断用户名是否存在
        QueryWrapper<SshUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        List<SshUser> userList = userMapper.selectList(queryWrapper);

        if (userList.size() == 0) {
            throw new BusinessException(SshCodeMsg.LOGIN_USERNAME_ERROR);
        }
        SshUser sshUser = userList.get(0);
        System.out.println("role" + sshUser.getRole());
        //判断用户是否是管理员
        if (sshUser.getRole() != 0) {
            throw new BusinessException(SshCodeMsg.LOGIN_PERMISSION_ERROR);
        }


        //判断密码是否正确
        if (MD5Util.getMD5(user.getPassword()).equals(sshUser.getPassword())) {
            String token = TokenGenerator.generateToken();
            //设置token过期时间为一小时
            redisTemplate.opsForValue().set(token, String.valueOf(sshUser.getUserId()), 3600, TimeUnit.SECONDS);
            return token;
        } else {
            throw new BusinessException(SshCodeMsg.LOGIN_PASSWORD_ERROR);
        }

    }

    /**
     * 获取用户的连接信息
     *
     * @param token 当前登录用户的token
     * @return 当前用户连接的服务
     */
    @Override
    public List<SshConnect> getConnectMsg(String token) {


        String userId = redisTemplate.opsForValue().get(token);
        QueryWrapper<SshConnect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<SshConnect> sshConnects = userConnectMapper.selectList(queryWrapper);
        System.out.println(userId);

        if (sshConnects.size() != 0) {
            return sshConnects;
        }

        return null;
    }


}
